<?php
class WPaymentAuthorizenetAuthorize extends USystemWorklet
{
	public $paymentAction = 'AUTH_ONLY';
	
	public function accessRules()
	{
		return array(
			array('deny', 'users'=>array('?'))
		);
	}
	
	public function run($items,$orderId=null,$options=array())
	{
		include_once(dirname(__FILE__).'/../components/anet_php_sdk/AuthorizeNet.php');
		
		$url = 'https://secure.authorize.net/gateway/transact.dll';
		if($this->param('sandbox'))
			$url = 'https://test.authorize.net/gateway/transact.dll';
			
		$amount = 0;
		foreach($items as $key=>$val)
		{
			if(is_array($val))
				$amount+= $val['price']*$val['quantity'];
		}
		
		$tstamp = time();			
		$fields = array(
			'x_login' => $this->param('apiLogin'),
			'x_fp_hash' => AuthorizeNetSIM_Form::getFingerprint($this->param('apiLogin'),
				$this->param('apiTransactionKey'), $amount, $orderId, $tstamp),
			'x_fp_timestamp' => $tstamp,
			'x_fp_sequence' => $orderId,
			'x_amount' => $amount,
			'x_relay_url' => isset($options['notify_url'])?$options['notify_url']:aUrl('/payment/authorizenet/ipn'),
			'x_relay_response' => 'TRUE',
			'x_invoice_num' => $orderId,
			'x_show_form' => 'payment_form',
			'x_test_request' => 'false',
			'x_method' => 'cc',
			'x_type' => $this->paymentAction,
		);
		
		$html = CHtml::beginForm($url,'post',array('id'=>'paymentForm'));
		foreach ($fields as $name => $value)
			$html.= CHtml::hiddenField($name,$value);
		$html.= CHtml::endForm();
		$html.= CHtml::script('jQuery("#paymentForm").submit();');
		
		if(app()->request->isAjaxRequest)
			wm()->get('base.init')->addToJson(array(
				'keepDisabled' => true,
				'content' => array(
					'append' => $html,
					'focus' => true,
				),
			));
		else
			return $html;
	}
}